<template>
  <div class="farmer-qa">
    <!-- 头部 -->
    <div class="header-section">
      <div class="header-title">
        <el-icon class="title-icon"><ChatDotRound /></el-icon>
        <h1>线上答疑</h1>
      </div>
      <div class="header-subtitle">
        <p>与各位专家实时互动，咨询疑点，解决问题</p>
      </div>
    </div>

    <!-- 等待答疑列表 -->
    <div v-if="!currentSession" class="waiting-list">
      <h3>等待答疑的专家</h3>
      <div class="expert-list">
        <div 
          v-for="expert in waitingExperts" 
          :key="expert.id" 
          class="expert-card"
          :class="{ 'ready': isReadyToStart(expert) }"
        >
          <div class="expert-info">
            <div class="expert-avatar">{{ expert.name.charAt(0) }}</div>
            <div class="expert-details">
              <h4>{{ expert.name }}</h4>
              <p class="expert-title">{{ expert.title }}</p>
              <p class="problem-preview">{{ expert.specialty }}</p>
              <div class="appointment-time">
                <i class="fas fa-clock"></i>
                {{ expert.appointmentTime }}
              </div>
            </div>
          </div>
          <div class="expert-actions">
            <button 
              class="btn primary-btn" 
              @click="startSession(expert)"
              :disabled="!isReadyToStart(expert)"
            >
              {{ isReadyToStart(expert) ? '开始咨询' : '等待时间' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="waitingExperts.length === 0" class="empty-state">
        <div class="empty-icon">💬</div>
        <h3>暂无等待答疑的专家</h3>
        <p>专家的预约将在到达时间后显示在这里</p>
      </div>
    </div>

    <!-- 答疑会话界面 -->
    <div v-else class="qa-session">
      <div class="session-header">
        <div class="expert-info-header">
          <div class="expert-avatar-header">{{ currentSession.expertName.charAt(0) }}</div>
          <div class="expert-details-header">
            <h3>{{ currentSession.expertName }}</h3>
            <p class="expert-title-header">{{ currentSession.expertTitle }}</p>
          </div>
        </div>
        <div class="session-info">
          <div class="chat-actions">
            <!-- 问题详情按钮 -->
            <el-button type="primary" text @click="showProblemDetail = true">
              <el-icon><Document /></el-icon>
              问题详情
            </el-button>
          </div>
          <span class="session-timer">
            <i class="fas fa-clock"></i>
            {{ formatTimeCount(sessionTimer) }}
          </span>
          <button class="button" @click="endSession">
            <i class="fas fa-times"></i> 结束咨询
          </button>
        </div>
      </div>

      <div class="chat-container">
        <div class="messages-container" ref="messagesContainer">
          <div 
            v-for="message in currentSession.messages" 
            :key="message.id"
            class="message"
            :class="message.sender"
          >
            <div class="message-content">
              {{ message.content }}
            </div>
            <div class="message-time">
              {{ message.time }}
            </div>
          </div>
        </div>

        <div class="message-input">
          <textarea 
            v-model="newMessage" 
            placeholder="请输入您的问题..."
            rows="3"
            @keypress.enter.prevent="sendMessage"
          ></textarea>
          <button class="btn primary-btn" @click="sendMessage" :disabled="!newMessage.trim()">
            <i class="fas fa-paper-plane"></i> 发送
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 问题详情对话框 -->
  <el-dialog
    v-model="showProblemDetail"
    title="问题详情"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="problem-detail-content">
      <div class="detail-item">
        <span class="label">咨询问题:</span>
        <span class="value">{{ problemDetail.problemDescription }}</span>
      </div>
      
      <div class="detail-item">
        <span class="label">预约类型:</span>
        <span class="value">{{ problemDetail.appointmentType === 1 ? '线上答疑' : '线下预约' }}</span>
      </div>
      
      <div class="detail-item">
        <span class="label">开始时间:</span>
        <span class="value">{{ formatTime(problemDetail.startTime) }}</span>
      </div>
      
      <div class="detail-item">
        <span class="label">咨询状态:</span>
        <span class="value">
          <el-tag type="success" size="small">进行中</el-tag>
        </span>
      </div>
    </div>
  </el-dialog>

  <!-- 评分对话框 -->
  <el-dialog
    v-model="showRatingDialog"
    title="请对本次咨询服务评分"
    width="400px"
    :close-on-click-modal="false"
    :show-close="false"
  >
    <div class="rating-dialog-content">
      <div class="rating-title">您的满意度如何？</div>
      <div class="rating">
        <input type="radio" id="star-5" name="star-radio" value="5" v-model="rating">
        <label for="star-5">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path></svg>
        </label>
        <input type="radio" id="star-4" name="star-radio" value="4" v-model="rating">
        <label for="star-4">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path></svg>
        </label>
        <input type="radio" id="star-3" name="star-radio" value="3" v-model="rating">
        <label for="star-3">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path></svg>
        </label>
        <input type="radio" id="star-2" name="star-radio" value="2" v-model="rating">
        <label for="star-2">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path></svg>
        </label>
        <input type="radio" id="star-1" name="star-radio" value="1" v-model="rating">
        <label for="star-1">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path></svg>
        </label>
      </div>
      <div class="rating-submit">
        <el-button @click="submitRating" type="primary" :disabled="rating === 0">提交评分</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessageBox } from 'element-plus'

// 响应式数据
const currentSession = ref(null)
const newMessage = ref('')
const sessionTimer = ref(0)
const messagesContainer = ref(null)
let timerInterval = null

const showProblemDetail = ref(false) // 控制问题详情对话框显示

const showRatingDialog = ref(false)  // 控制评分对话框显示
const rating = ref(0)  // 存储评分值

// 问题详情
const problemDetail = reactive({
  id: 1,
  problemDescription: '关于西红柿种植过程中的病虫害防治问题，特别是针对白粉病和蚜虫的有效防治方法。',
  appointmentType: 1,
  startTime: new Date().toISOString(),
  status: 1
})

// 等待答疑的专家列表
const waitingExperts = ref([
  {
    id: 1,
    name: '张教授',
    title: '农业种植专家',
    specialty: '蔬菜种植、果树栽培、土壤改良',
    appointmentTime: '14:30',
    appointmentDate: '2024-01-25',
    status: 'ready'
  },
  {
    id: 2,
    name: '李博士',
    title: '植物保护专家',
    specialty: '病虫害防治、农药使用、生物防治',
    appointmentTime: '15:00',
    appointmentDate: '2024-01-25',
    status: 'waiting'
  },
  {
    id: 3,
    name: '王工程师',
    title: '农业机械专家',
    specialty: '农机操作、设备维护、机械化种植',
    appointmentTime: '16:30',
    appointmentDate: '2024-01-25',
    status: 'waiting'
  }
])

// 方法
const isReadyToStart = (expert) => {
  return expert.status === 'ready'
}

const startSession = (expert) => {
  currentSession.value = {
    expertId: expert.id,
    expertName: expert.name,
    expertTitle: expert.title,
    startTime: new Date(),
    messages: [
      {
        id: 1,
        sender: 'farmer',
        content: '专家您好，我的西红柿最近出现了白粉病，请问有什么有效的防治方法吗？',
        time: '14:30'
      },
      {
        id: 2,
        sender: 'expert',
        content: '您好！白粉病是西红柿常见的病害。建议使用25%嘧菌酯悬浮剂1500倍液喷雾，每隔7-10天喷一次，连续2-3次。',
        time: '14:32'
      },
      {
        id: 3,
        sender: 'expert',
        content: '同时要注意通风透光，避免种植过密，及时清除病叶病果。',
        time: '14:33'
      },
      {
        id: 4,
        sender: 'farmer',
        content: '谢谢专家！另外还有蚜虫的问题，应该怎么处理？',
        time: '14:35'
      }
    ]
  }
  
  // 开始计时
  sessionTimer.value = 0
  timerInterval = setInterval(() => {
    sessionTimer.value++
  }, 1000)

  // 从等待列表中移除
  waitingExperts.value = waitingExperts.value.filter(f => f.id !== expert.id)
  scrollToBottom()
}

const endSession = () => {
  // 显示确认对话框
  ElMessageBox.confirm('确定要结束本次答疑吗？', '结束答疑', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'end-session-confirm'
  }).then(() => {
    // 用户确认结束
    if (timerInterval) {
      clearInterval(timerInterval)
    }
    
    // 保存会话记录
    if (currentSession.value) {
      const sessionRecord = {
        ...currentSession.value,
        endTime: new Date(),
        duration: sessionTimer.value
      }
      console.log('保存会话记录:', sessionRecord)
    }
    
    // 显示评分对话框而不是直接重置会话
    showRatingDialog.value = true
    
  }).catch(() => {
    // 用户取消，什么都不做
    console.log('用户取消结束答疑')
  })
}

const submitRating = () => {
  console.log('提交评分:', rating.value)
  // 这里可以发送评分到服务器
  showRatingDialog.value = false
  // 重置会话
  currentSession.value = null
  sessionTimer.value = 0
}

const sendMessage = () => {
  if (!newMessage.value.trim()) return

  const message = {
    id: Date.now(),
    sender: 'farmer',
    content: newMessage.value,
    time: new Date().toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }

  currentSession.value.messages.push(message)
  newMessage.value = ''

  // 模拟专家回复
  setTimeout(() => {
    const expertReply = {
      id: Date.now() + 1,
      sender: 'expert',
      content: '针对蚜虫问题，可以使用10%吡虫啉可湿性粉剂2000倍液喷雾防治，注意叶片正反面都要喷到。',
      time: new Date().toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
    currentSession.value.messages.push(expertReply)
    scrollToBottom()
  }, 2000)

  scrollToBottom()
}

const formatTimeCount = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

const formatTime = (timeString) => {
  return new Date(timeString).toLocaleString('zh-CN')
}

onMounted(() => {
  // 可以在这里加载等待答疑的专家列表
})

onUnmounted(() => {
  if (timerInterval) {
    clearInterval(timerInterval)
  }
})
</script>

<style scoped>
/* 头部样式 */
.header-section {
  text-align: center;
  margin-bottom: 24px;
  padding: 40px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
}

.header-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-bottom: 12px;
}

.title-icon {
  font-size: 40px;
}

.header-title h1 {
  margin: 0;
  font-size: 36px;
  font-weight: 700;
}

.header-subtitle p {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
}

.farmer-qa {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  color: #333;
  font-size: 24px;
  margin: 0;
}

.waiting-list h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
}

.expert-list {
  display: grid;
  gap: 15px;
}

.expert-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 4px solid #FF9800;
  transition: all 0.3s ease;
}

.expert-card.ready {
  border-left-color: #4CAF50;
}

.expert-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}

.expert-info {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
}

.expert-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4CAF50, #2E7D32);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 20px;
  flex-shrink: 0;
}

.expert-details h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.expert-title {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
}

.problem-preview {
  color: #888;
  margin: 0 0 8px 0;
  font-size: 13px;
}

.appointment-time {
  color: #999;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.expert-actions {
  flex-shrink: 0;
}

/* 答疑会话界面 */
.qa-session {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  overflow: hidden;
}

.session-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.expert-info-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.expert-avatar-header {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4CAF50, #2E7D32);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 18px;
}

.expert-details-header h3 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 18px;
}

.expert-title-header {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.session-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.session-timer {
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 600px;
}

.messages-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message.farmer {
  align-self: flex-end;
}

.message.expert {
  align-self: flex-start;
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
}

.message.farmer .message-content {
  background: #409eff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.expert .message-content {
  background: white;
  color: #333;
  border: 1px solid #e0e0e0;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 5px;
  padding: 0 8px;
}

.message-input {
  padding: 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
}

.message-input textarea:focus {
  outline: none;
  border-color: #409eff;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.primary-btn {
  background: #4CAF50;
  color: white;
}

.primary-btn:hover:not(:disabled) {
  background: #45a049;
  transform: translateY(-1px);
}

/* From Uiverse.io by gharsh11032000 */ 
.button {
  cursor: pointer;
  position: relative;
  padding: 10px 24px;
  font-size: 18px;
  color: rgb(193, 163, 98);
  border: 2px solid rgb(193, 163, 98);
  border-radius: 34px;
  background-color: transparent;
  font-weight: 600;
  transition: all 0.3s cubic-bezier(0.23, 1, 0.320, 1);
  overflow: hidden;
}

.button::before {
  content: '';
  position: absolute;
  inset: 0;
  margin: auto;
  width: 50px;
  height: 50px;
  border-radius: inherit;
  scale: 0;
  z-index: -1;
  background-color: rgb(193, 163, 98);
  transition: all 0.6s cubic-bezier(0.23, 1, 0.320, 1);
}

.button:hover::before {
  scale: 3;
}

.button:hover {
  color: #212121;
  scale: 1.1;
  box-shadow: 0 0px 20px rgba(193, 163, 98,0.4);
}

.button:active {
  scale: 1;
}

/* 问题详情对话框样式 */
.problem-detail-content {
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item .label {
  color: #718096;
  font-size: 14px;
  min-width: 80px;
}

.detail-item .value {
  color: #2d3748;
  font-weight: 500;
  flex: 1;
}

/* 问题详情对话框样式 */
.session-info {
  margin-bottom: 20px;
}

.attachments-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.file-icon {
  font-size: 24px;
  color: #409eff;
}

.file-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 2px;
}

.file-size {
  font-size: 12px;
  color: #909399;
}

/* 评分对话框样式 */
.rating-dialog-content {
  text-align: center;
}

.rating-title {
  font-size: 16px;
  margin-bottom: 20px;
  color: #333;
}

.rating {
  display: flex;
  flex-direction: row-reverse;
  justify-content: center;
  gap: 0.3rem;
  --stroke: #666;
  --fill: #ffc73a;
  margin-bottom: 20px;
}

.rating input {
  appearance: unset;
}

.rating label {
  cursor: pointer;
}

.rating svg {
  width: 2rem;
  height: 2rem;
  overflow: visible;
  fill: transparent;
  stroke: var(--stroke);
  stroke-linejoin: bevel;
  stroke-dasharray: 12;
  animation: idle 4s linear infinite;
  transition: stroke 0.2s, fill 0.5s;
}

@keyframes idle {
  from {
    stroke-dashoffset: 24;
  }
}

.rating label:hover svg {
  stroke: var(--fill);
}

.rating input:checked ~ label svg {
  transition: 0s;
  animation: idle 4s linear infinite, yippee 0.75s backwards;
  fill: var(--fill);
  stroke: var(--fill);
  stroke-opacity: 0;
  stroke-dasharray: 0;
  stroke-linejoin: miter;
  stroke-width: 8px;
}

@keyframes yippee {
  0% {
    transform: scale(1);
    fill: var(--fill);
    fill-opacity: 0;
    stroke-opacity: 1;
    stroke: var(--stroke);
    stroke-dasharray: 10;
    stroke-width: 1px;
    stroke-linejoin: bevel;
  }

  30% {
    transform: scale(0);
    fill: var(--fill);
    fill-opacity: 0;
    stroke-opacity: 1;
    stroke: var(--stroke);
    stroke-dasharray: 10;
    stroke-width: 1px;
    stroke-linejoin: bevel;
  }

  30.1% {
    stroke: var(--fill);
    stroke-dasharray: 0;
    stroke-linejoin: miter;
    stroke-width: 8px;
  }

  60% {
    transform: scale(1.2);
    fill: var(--fill);
  }
}

.rating-submit {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .farmer-qa {
    padding: 16px;
  }
  
  .expert-card {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .expert-actions {
    align-self: flex-end;
  }
  
  .session-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .session-info {
    align-self: flex-end;
  }
  
  .message {
    max-width: 85%;
  }
  
  .message-input {
    flex-direction: column;
  }
  
  .message-input button {
    width: 100%;
  }
}
</style>